package com.nulldev.util.io.bit.miscellaneous;

import java.io.IOException;
import java.util.Objects;

import com.nulldev.util.io.bit.BitInput;
import com.nulldev.util.io.bit.LongReader;

/**
 * A reader for reading VLQ-encoded values.
 *
 * @author Jin Kwon &lt;onacit_at_gmail.com&gt;
 */
public class VlqReader
        implements LongReader {

    private static final class InstanceHolder {

        private static final VlqReader INSTANCE = new VlqReader();

        private InstanceHolder() {
            throw new AssertionError(BitIoMiscellaneousConstants.MESSAGE_INPUT_IS_NULL);
        }
    }

    /**
     * Returns the instance of this writer. The {@code VlqReader} is singleton.
     *
     * @return the instance of this writer.
     */
    public static VlqReader getInstance() {
        return InstanceHolder.INSTANCE;
    }

    /**
     * Creates a new instance.
     */
    private VlqReader() {
        super();
    }

    @Override
    public long readLong(final BitInput input) throws IOException {
        Objects.requireNonNull(input, "input is null");
        long value = 0L;
        while (true) {
            final int last = input.readInt(true, 1);
            value <<= 7;
            value |= input.readLong(true, 7);
            if (last == 0) {
                break;
            }
        }
        return value;
    }
}
